const api = require('../../config/api.js');
const app = getApp();
let that;
Page({
  data: {
    RootUrl: api.RootUrl,
    ImgRootUrl: app.globalData.ImgRootUrl,
    version: app.globalData.version,
    cartGoods: [],
    cartTotal: {
      "goodsCount": 0,
      "goodsAmount": 0.00,
      "checkedGoodsCount": 0,
      "checkedGoodsAmount": 0.00
    },
    isEditCart: false,
    isLogin: false,
    checkedAllStatus: true,
    editCartList: []
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
    this.getCartList();
    //退出编辑状态
    this.setData({
      isEditCart: false
    });
    //检查登陆
    let isLogin = wx.getStorageSync('token');
    if (isLogin) {
      this.setData({
        isLogin: true
      })
    }else{
      this.setData({
        isLogin: false
      })
    }
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  //获取购物车商品列表
  getCartList: function () {
    app.util.request(api.CartList, {random: Math.random()}).then(function (res) {
      if (res.errno === 0) {
        //console.log(res.data);
        app.globalData.cartGoodsCount = res.data.cartTotal.goodsCount;
        app.cart.setCartBadge(res.data.cartTotal.goodsCount);
        that.setData({
          cartGoods: res.data.cartList,
          cartTotal: res.data.cartTotal
        });
      } else {
        app.util.showToast(res.error);
      }
      that.setData({
        checkedAllStatus: that.isCheckedAll()
      });
    });
  },
  //判断购物车商品是否全选
  isCheckedAll: function () {
    return this.data.cartGoods.every(function (element, index, array) {
      if (element.checked == 1) {
        return true;
      } else {
        return false;
      }
    });
  },
  //点选商品时，获取未选商品的ids
  getUnProductIds: function (i) {
    let _cartGoods = this.data.cartGoods;
    _cartGoods[i].checked = !_cartGoods[i].checked;
    this.setData({
      ["cartGoods[" + i + "].checked"]: _cartGoods[i].checked
    });
    let productIds = _cartGoods.filter(function (v) {
      if (v.checked == 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.ids;
    });
    return productIds.join(',');
  },
  //[通用] 获取商品的ids数组，参数：1已选,0未选
  getIdsArray: function (i = 1) {
    let productIds = this.data.cartGoods.filter(function (v) {
      if (v.checked == i) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.ids;
    });
    return productIds;
  },
  //点选商品
  checkedItem: function (event) {
    let i = event.currentTarget.dataset.i;    //索引
    if (!this.data.isEditCart) {
      let productIds = that.getUnProductIds(i);
      app.util.request(api.CartChecked, { productIds: productIds, random: Math.random() }).then(function (res) {
        if (res.errno === 0) {
          //console.log(res.data);
          that.setData({
            cartTotal: res.data.cartTotal
          });
        } else {
          app.util.showToast(res.error);
        }
        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let tmpCartData = this.data.cartGoods.map(function (element, index, array) {
        if (index == i){
          element.checked = !element.checked;
        }
        return element;
      });
      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }
  },
  //全选 反选
  checkedAll: function () {
    if (!this.data.isEditCart) {
      let ids = '';
      if (that.isCheckedAll()) {
        var productIds = this.data.cartGoods.map(function (v) {
          return v.ids;
        });
        ids = productIds.join(',')
      }
      app.util.request(api.CartChecked, { productIds: ids,random: Math.random() }).then(function (res) {
        if (res.errno === 0) {
          //console.log(res.data);
          that.setData({
            cartGoods: res.data.cartList,
            cartTotal: res.data.cartTotal
          });
        } else {
          app.util.showToast(res.error);
        }
        that.setData({
          checkedAllStatus: that.isCheckedAll()
        });
      });
    } else {
      //编辑状态
      let checkedAllStatus = that.isCheckedAll();
      let tmpCartData = this.data.cartGoods.map(function (v) {
        v.checked = !checkedAllStatus;
        return v;
      });
      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }
  },
  //编辑购物车
  editCart: function () {
    if (this.data.isEditCart) {
      //删除商品
      let productIds = this.getIdsArray(1);
      if (productIds.length <= 0) {
        app.util.showToast('请选择您想删除的商品');
        return false;
      }
      // productIds.join(',')
      wx.showModal({
        title: '',
        content: '确定删除所选商品？',
        confirmColor: '#b4282d',
        success: function (res) {
          if (res.confirm) {
            app.util.request(api.CartDelete, { productIds: productIds, random: Math.random() }, 'POST').then(function (res) {
              if (res.errno === 0) {
                app.util.showToast('删除成功');
                let cartList = res.data.cartList.map(v => {
                  v.checked = 0;
                  return v;
                });
                app.globalData.cartGoodsCount = res.data.cartTotal.goodsCount;
                app.cart.setCartBadge(res.data.cartTotal.goodsCount);
                that.setData({
                  cartGoods: cartList,
                  cartTotal: res.data.cartTotal
                });
              } else {
                app.util.showToast(res.error);
              }
              that.setData({
                checkedAllStatus: that.isCheckedAll()
              });
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      //进入编辑状态
      let tmpCartList = this.data.cartGoods.map(function (v) {
        v.checked = 0;
        return v;
      });
      this.setData({
        editCartList: this.data.cartGoods,
        cartGoods: tmpCartList,
        isEditCart: !this.data.isEditCart,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    }
  },
  //编辑状态下，获取选中的商品数量
  getCheckedGoodsCount: function () {
    let checkedGoodsCount = 0;
    this.data.cartGoods.forEach(function (v) {
      if (v.checked == 1) {
        checkedGoodsCount += v.count;
      }
    });
    //console.log(checkedGoodsCount);
    return checkedGoodsCount;
  },
  //减
  cutNumber: function (event) {
    let i = event.currentTarget.dataset.i;
    let cartItem = this.data.cartGoods[i];
    let number = cartItem.count - 1;
    if (number <= 0) {
      return false;
    }
    this.setData({
      ["cartGoods[" + i + "].count"]: number
    });
    this.updateCart(cartItem.product_id, cartItem.goods_id, -1);
  },
  //加
  addNumber: function (event) {
    let i = event.currentTarget.dataset.i;
    let cartItem = this.data.cartGoods[i];
    let number = cartItem.count + 1;
    //非实时：验证库存
    if (cartItem.store_nums < number) {
      //提示剩余库存
      wx.showToast({
        icon: 'none',
        title: '库存不足，剩余：' + cartItem.store_nums,
        mask: true
      });
      return false;
    }
    this.setData({
      ["cartGoods[" + i + "].count"]: number
    });
    this.updateCart(cartItem.product_id, cartItem.goods_id, 1);
  },
  //更新购物车
  updateCart: function (productId, goodsId, number) {
    app.util.request(api.CartUpdate, {
      productId: productId,
      goodsId: goodsId,
      number: number,
      random: Math.random()
    }).then(function (res) {
      if (res.errno === 0) {
        app.globalData.cartGoodsCount = res.data.cartTotal.goodsCount;
        app.cart.setCartBadge(res.data.cartTotal.goodsCount);
      }else{
        app.util.showToast(res.error);
      }
      that.setData({
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
      });
    });

  },
  //退出编辑状态
  exitEdit: function () {
    this.getCartList();
    this.setData({
      isEditCart: !this.data.isEditCart
    });
  },
  //下单
  checkoutOrder: function () {
    //获取已选择的商品
    var checkedGoods = this.getIdsArray(1);
    console.log(checkedGoods);
    if (checkedGoods.length <= 0) {
      return false;
    }
    wx.navigateTo({
      url: '../shopping/checkout/checkout'
    })
  },
  //用户授权登陆
  getUserInfo: function (e) {
    console.log('cart.js', e)
    //授权登陆
    app.user.loginByWeixin().then(res => {
      app.globalData.userInfo = res.data.userInfo;
      app.globalData.Refresh = true;
      that.onShow();
    }).catch((err) => {
      console.log(err)
    });
  },
})